package com.wing.res.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;

import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.model.response.ProductPlanningTreeVo;


import com.wing.product.service.ProductUnitService;
import com.wing.res.model.entity.ResProEchnologyParamVersionSku;
import com.wing.res.model.entity.ResProductDraw;
import com.wing.res.model.entity.ResProductMoldDraw;
import com.wing.res.model.request.*;
import com.wing.res.model.response.ResProTaskDetailVo;
import com.wing.res.model.response.ResProTaskSearchVo;
import com.wing.res.service.*;
import com.wing.sell.model.entity.OrderProEnclosure;
import com.wing.sell.service.OrderProEnclosureService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生产研发任务
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-19 15:36
 **/
@Slf4j
@Validated
@Api(value = "生产研发任务管理", tags = "#/res/planning/proTask")
@RestController("resProTaskController")
@RequestMapping("res/admin/planning/proTask")
public class ResProTaskController {

    @Resource
    private ResProTaskService resProTaskService;

    @Resource
    private ProductUnitService productUnitService;

    @Resource
    private ResProductDrawService resProductDrawService;

    @Resource
    private ResProductMoldDrawService resProductMoldDrawService;

    @Resource
    private ResProEchnologyParamService resProEchnologyParamService;

    @Resource
    private ResProEchnologyParamVersionSkuService resProEchnologyParamVersionSkuService;

    @Resource
    private ResProQualityProjectService resProQualityProjectService;

    @Resource
    private OrderProEnclosureService orderProEnclosureService;

    @ApiOperation(value = "查研发任务列表", notes = "搜索-任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ResProTaskSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long productTypeId
            ,Long customerId
            ,String customerProCode
            ,String productStatus
            ,String customerProFigure
            ,String givenStartTimed
    ) {
        Page<ResProTaskSearchVo> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("customerProCode", customerProCode);
        map.put("productStatus", productStatus);
        if (StrUtil.isNotEmpty(givenStartTimed)){
            // 使用 split 方法分割字符串
            String[] dates = givenStartTimed.split(" 至 ");
            // 获取开始和结束日期
            String startDate = dates[0];
            String endDate = dates[1];
            map.put("givenStartTime", startDate);
            map.put("givenEndTime", endDate);
        }
        map.put("customerProFigure", customerProFigure);
        map.put("productTypeId", productTypeId);
        String noStatus = "";
        Page<ResProTaskSearchVo> list = resProTaskService.pageList4app(pg, map, noStatus);
        list.getRecords().forEach(info-> {
                    info.setProductStatus(MaintenanceEnum.Task_Status_Enum.getNameByCode(info.getProductStatus()));
                    info.setSource(MaintenanceEnum.Task_Source_Enum.getNameByCode(info.getSource()));
                    QueryWrapper<OrderProEnclosure> enclosureQueryWrapper = new QueryWrapper<>();
                    enclosureQueryWrapper.eq("task_id",info.getId());
            OrderProEnclosure one = orderProEnclosureService.getOne(enclosureQueryWrapper);
            if (ObjectUtil.isNotEmpty(one)){
                info.setFileUrl(one.getFileUrl());
                info.setCusProductFigure(one.getFileName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加研发任务", notes = "添加-研发任务")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody ResProTaskAddForm resProTaskAddForm) {
        if (resProTaskService.add(resProTaskAddForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败!物料编码重复！");
    }

    @ApiOperation(value = "修改研发任务", notes = "修改-研发任务")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/update")
    public JsonResult update(@RequestBody ResProTaskAddForm resProTaskAddForm) {
        if (resProTaskService.updateInfo(resProTaskAddForm) > 0) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }


    /**
     * 初始化任务详情
     * @param id
     * @return
     */
    @ApiOperation(value = "查看研发任务详情", notes = "查看")
    @GetMapping("/detail/{id}")
    public JsonResult resProTaskDetail(@PathVariable("id") String id) {
        ResProTaskDetailVo taskDetail =  resProTaskService.resProTaskDetail(id);
        if (taskDetail == null) {
            return JsonResult.fail("获取详情失败！");
        }

        //查出所有计量方式和单位
        List<ProductUnitInfo> infoList = productUnitService.list();
        for (ProductUnitInfo productUnitInfo : infoList) {
            if (taskDetail.getMainUnitId()!=null){
                if (ObjectUtil.isNotEmpty(taskDetail.getMainUnitId()) && taskDetail.getMainUnitId().equals(productUnitInfo.getId())) {
                    taskDetail.setMainUnitName(productUnitInfo.getName());
                }
                if (ObjectUtil.isNotEmpty(taskDetail.getSubUnitId()) && taskDetail.getSubUnitId().equals(productUnitInfo.getId())) {
                    taskDetail.setSubUnitName(productUnitInfo.getName());
                }
            }
        }
        //是否关联新产品
        if (StrUtil.isNotEmpty(taskDetail.getIsUseOrAdd())){
            taskDetail.setIsUseOrAdd(ProductEnum.ReviewUseOrNewEmum.getNameByCode(taskDetail.getIsUseOrAdd()));
        }
        //赋值结果
        if (taskDetail.getProductTypeId()!=null){
            QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("type", 0);
            wrapper.eq("product_type", taskDetail.getProductTypeId());
            wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
            wrapper.eq("is_base_unit", "1");
            ProductUnitInfo productUnitInfo = productUnitService.getOne(wrapper);
            //赋值基础单位
            if (ObjectUtil.isNotEmpty(productUnitInfo)) {
                taskDetail.setInUnitName(productUnitInfo.getName());
            }
        }
        QueryWrapper<ResProductDraw> queryWrapper = new QueryWrapper<ResProductDraw>();
        queryWrapper.eq("is_default",'1');
        queryWrapper.eq("product_detail_id",taskDetail.getProductDetailId());
        queryWrapper.eq("task_id",taskDetail.getId());
        ResProductDraw one = resProductDrawService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one) && one.getIsRelevance().equals(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode())){
            QueryWrapper<ResProductMoldDraw> moldWrapper = new QueryWrapper<ResProductMoldDraw>();
            moldWrapper.eq("is_default",'1');
            moldWrapper.eq("draw_id",one.getId());
//            moldWrapper.eq("draw_version",one.getVersionName());
            ResProductMoldDraw draw = resProductMoldDrawService.getOne(moldWrapper);
            MoldDrawInfo info = new MoldDrawInfo();
            BeanUtil.copyProperties(draw, info,true);
            one.setMoldDrawInfo(info);
        }

        //初始化工序信息
        List<ProcessProjectData> oldVersionInfo = resProEchnologyParamService.getOldVersionInfoById(taskDetail.getId());
        if (CollectionUtils.isNotEmpty(oldVersionInfo)) {
            for (ProcessProjectData processProjectData : oldVersionInfo) {
                Long paramsId = processProjectData.getParamsId();
                if (ObjectUtil.isNotNull(paramsId)){
                    //查询当前主参数关联的物料列表
                   List<ResProEchnologyParamVersionSku> skus = this.resProEchnologyParamVersionSkuService.getListSkuInfoBy(paramsId);
                   processProjectData.setVersionSkuList(skus);
                }
            }
        }
        taskDetail.setProcessProjectData(oldVersionInfo);

        //初始化检测项目信息
        List<TestItemData> testItemData = resProQualityProjectService.getProjectInfoById(taskDetail.getProductDetailId());
        if (CollectionUtils.isNotEmpty(testItemData)){
            taskDetail.setTestItemData(testItemData);
        }
        taskDetail.setDrawInfo(one);
        if (StrUtil.isNotEmpty(taskDetail.getStatus())){
            taskDetail.setStatusName(MaintenanceEnum.Task_Status_Enum.getNameByCode(taskDetail.getStatus()));
            taskDetail.setSource(MaintenanceEnum.Task_Source_Enum.getNameByCode(taskDetail.getSource()));
        }
        return JsonResult.success("获取成功！",taskDetail);
    }

    /**
     * 初始化任务详情
     * @param skuCode 物料编码
     * @return
     */
    @ApiOperation(value = "查看研发任务详情", notes = "查看")
    @GetMapping("/detail")
    public JsonResult detail(@RequestParam("skuCode") String skuCode) {
        ResProTaskDetailVo taskDetail = new ResProTaskDetailVo();
        List<ResProTaskDetailVo> taskDetails =  resProTaskService.getProTaskDetailBySkuCode(skuCode);
        if (CollectionUtil.isNotEmpty(taskDetails)){
            taskDetail = taskDetails.get(0);
        }
        if (taskDetail == null) {
            return JsonResult.fail("获取详情失败！");
        }
        //是否关联新产品
        if (StrUtil.isNotEmpty(taskDetail.getIsUseOrAdd())){
            taskDetail.setIsUseOrAdd(ProductEnum.ReviewUseOrNewEmum.getNameByCode(taskDetail.getIsUseOrAdd()));
        }
        //赋值结果
        if (taskDetail.getProductTypeId()!=null){
            QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("type", 0);
            wrapper.eq("product_type", taskDetail.getProductTypeId());
            wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
            wrapper.eq("is_base_unit", "1");
            ProductUnitInfo productUnitInfo = productUnitService.getOne(wrapper);
            if (ObjectUtil.isNotEmpty(productUnitInfo)) {
                //赋值基础单位
                taskDetail.setInUnitName(productUnitInfo.getName());
            }
        }
        QueryWrapper<ResProductDraw> queryWrapper = new QueryWrapper<ResProductDraw>();
        queryWrapper.eq("is_default",'1');
        queryWrapper.eq("product_detail_id",taskDetail.getProductDetailId());
        queryWrapper.eq("task_id",taskDetail.getId());
        ResProductDraw one = resProductDrawService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one) && one.getIsRelevance().equals(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode())){
            QueryWrapper<ResProductMoldDraw> moldWrapper = new QueryWrapper<ResProductMoldDraw>();
            moldWrapper.eq("is_default",'1');
            moldWrapper.eq("draw_id",one.getId());
//            moldWrapper.eq("draw_version",one.getVersionName());
            ResProductMoldDraw draw = resProductMoldDrawService.getOne(moldWrapper);
            if (ObjectUtil.isNotEmpty(draw)){
                MoldDrawInfo info = new MoldDrawInfo();
                BeanUtil.copyProperties(draw, info,true);
                one.setMoldDrawInfo(info);
            }
        }

        //初始化工序信息
        List<ProcessProjectData> oldVersionInfo = resProEchnologyParamService.getOldVersionInfoById(taskDetail.getId());
        taskDetail.setProcessProjectData(oldVersionInfo);

        //初始化检测项目信息
        List<TestItemData> testItemData = resProQualityProjectService.getProjectInfoById(taskDetail.getProductDetailId());
        taskDetail.setTestItemData(testItemData);
        taskDetail.setDrawInfo(one);
        if (StrUtil.isNotEmpty(taskDetail.getStatus())){
            taskDetail.setStatusName(MaintenanceEnum.Task_Status_Enum.getNameByCode(taskDetail.getStatus()));
            taskDetail.setSource(MaintenanceEnum.Task_Source_Enum.getNameByCode(taskDetail.getSource()));
        }
        return JsonResult.success("获取成功！",taskDetail);
    }

    /**
     * 添加产品工序
     * @param resProProcessAddForm
     * @return
     */
    @ApiOperation(value = "添加产品工序", notes = "添加产品工序")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addSkuProcess")
    public JsonResult addSkuProcess(@RequestBody ResProProcessAddForm resProProcessAddForm) {
        if (resProTaskService.addSkuProcess(resProProcessAddForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    /**
     * 添加sku检测项
     * @param resProQualityAddForm
     * @return
     */
    @ApiOperation(value = "添加sku检测项", notes = "添加sku检测项")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addSkuQuality")
    public JsonResult addSkuQuality(@RequestBody ResProQualityAddForm resProQualityAddForm) {
        if (resProTaskService.addSkuQuality(resProQualityAddForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    /**
     * 确认
     * @param id
     * @return
     */
    @ApiOperation(value = "点击确认", notes = "确认")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/confirm/{id}")
    public JsonResult confirm(@PathVariable("id") String id) {
        if (resProTaskService.confirm(id) > 0) {
            return JsonResult.success("操作成功");
        }
        return JsonResult.fail("操作失败");
    }


    /**
     * 提交校对
     * @param id
     * @return
     */
    @ApiOperation(value = "提交校对", notes = "提交校对")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/submitProofread/{id}")
    public JsonResult submitProofread(@PathVariable("id") String id) {
        if (resProTaskService.submitProofread(id) > 0) {
            return JsonResult.success("操作成功");
        }
        return JsonResult.fail("操作失败");
    }

}
